<template>
  <div class="page-wrapper">
    <el-card>
      <el-tabs>
        <!-- 第一标签页 -->
        <el-tab-pane label="角色管理">
          <!-- 按钮 -->
          <div class="tool-bar">
            <el-button type="primary" size="small" @click="isShowDialog=true">新增角色</el-button>
          </div>
          <!-- 表格 -->
          <el-table border :data="roleList">
            <el-table-column prop="index" width="80px" label="序号" />
            <el-table-column width="180px" label="角色名" prop="name" />
            <el-table-column label="描述" prop="description" />
            <el-table-column width="280px" label="操作">
              <template v-slot="scope">
                <el-button type="text" @click="showPermDialog(scope.row.id)">分配权限</el-button>
                <el-button type="text" @click="editRole(scope.row.id)">编辑角色</el-button>
                <el-button v-if="checkPerm('delrole')" type="text" @click="delRole(scope.row.id)">删除角色</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-row type="flex" justify="center" class="page-bar">
            <el-pagination :page-size="pageCongif.pagesize" :total="total" @current-change="currentChange" />
          </el-row>
        </el-tab-pane>
        <!-- 第二标签页 -->
        <el-tab-pane label="公司信息">
          <el-form label-width="80px">
            <el-form-item label="企业名称">
              <el-input v-model="companyInfo.name" disabled />
            </el-form-item>
            <el-form-item label="公司地址">
              <el-input v-model="companyInfo.companyAddress" disabled />
            </el-form-item>
            <el-form-item label="公司电话">
              <el-input v-model="companyInfo.companyPhone" disabled />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="companyInfo.mailbox" disabled />
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="companyInfo.remarks" disabled />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog :close-on-click-modal="false" :title="formData.id?'编制角色':'新增角色'" :visible="isShowDialog" @close="btnNO">
      <el-form ref="formData" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="formData.description" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small" type="primary" @click="btnOK">确定</el-button>
        <el-button size="small" @click="btnNO">取消</el-button>
      </template>
    </el-dialog>
    <el-dialog title="编辑角色的权限" :visible="isShowpremDialog" @close="btnPermCancel">
      <el-checkbox-group v-model="checkList">
        <!-- <el-checkbox
          v-for="item in permList"
          :key="item.id"
          :label="item.id"
        >{{ item.name }} -->
        <!-- </el-checkbox> -->
        <!-- 以上是v-for遍历列表渲染, 但是不支持树形 -->
        <!-- 使用树形组件, 用作用域插槽拿回数据替代 data -->
        <el-tree :data="permList" default-expand-all>
          <template v-slot="scope">
            <el-checkbox
              :label="scope.data.id"
            >
              {{ scope.data.name }}
            </el-checkbox>
          </template>
        </el-tree>
      </el-checkbox-group>
      <template #footer>
        <el-button size="small" type="primary" @click="btnPermOK">确定</el-button>
        <el-button size="small" @click="btnPermCancel">取消</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import { getSettingInfo, getRoleList, addRole, getIdRole, updateRole, deleteRole, assignPerm } from '@/api/setting'
import { getPermList } from '@/api/permission'
import { listToTree } from '@/utils'
export default {
  data() {
    return {
      isShowpremDialog: false,
      permList: [],
      // 存放被勾选后的id数组
      checkList: [],
      currentId: '',
      // 页面数据渲染
      pageCongif: {
        page: 1,
        pagesize: 2
      },
      total: 0,
      companyInfo: {},
      roleList: [],
      isShowDialog: false,
      formData: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '该项必填', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '该项必填', trigger: 'blur' }
        ]
      }
    }
  },
  async created() {
    const companyId = this.$store.state.user.userInfo.companyId
    const res = await getSettingInfo(companyId)
    console.log('59', res)
    this.companyInfo = res
    this.loadroleList()
    // 为了设置角色权限
    // 现货区全部权限数据
    const resPerm = await getPermList()
    console.log(resPerm)
    // this.permList = resPerm
    this.permList = listToTree(resPerm, '0')
    console.log(this.permList)
  },
  methods: {
    checkPerm(name) {
      const points = this.$store.state.user.userInfo.roles.points
      return points.indexOf(name) !== -1
    },
    async delRole(id) {
      try {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
        // 发送删除请求
        await deleteRole(id)
        // 更新页面数据有可能当前只剩下一条数据, 再次加载会变空
        // 可以通过数组长度判断, 看看要不要返回上一页(除了本身是在第一页除外)
        if (this.roleList.length === 1 && this.pageCongif.page > 1) {
          this.pageCongif.page--
        }
        // 更新页面数据
        this.loadroleList()
        // 提示用户
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    async currentChange(newPage) {
      console.log('点击了', newPage)
      this.pageCongif.page = newPage
      this.loadroleList()
    },
    async loadroleList() {
      const res2 = await getRoleList(this.pageCongif)
      console.log(res2)
      this.total = res2.total
      this.roleList = res2.rows.map((item, index) => {
        return {
          ...item,
          index: (this.pageCongif.page - 1) * this.pageCongif.pagesize + index + 1
        }
      })
    },
    async btnOK() {
      try {
        // 写要执行的逻辑
        // 如果这个逻辑任何一个地方出错,
        // 马上会跳到 catch
        // 校验表单
        await this.$refs.formData.validate()
        // 最重要发请求
        // 需要判断到底是新增还是编辑
        if (this.formData.id) {
          // 编辑
          await updateRole(this.formData)
        } else {
          // 新增
          await addRole(this.formData)
        }
        // 提醒用户
        this.$message.success('操作成功')
        // 关闭弹窗
        this.isShowDialog = false
        // 更新页面数据
        this.loadroleList()
      } catch (error) {
        // 一旦出错自动来到这, 需要程序员尝试错误(只要读取过就ok)
        console.log(error)
      }
    },
    btnNO() {
      // 这个函数可以清理报错, 并将绑定的表单数据恢复初始值(第一次打开表单绑定的数据)
      // // 编辑时会出问题 不能依赖, 需要手动清理数据
      this.formData = {
        name: '',
        description: ''
      }
      // 这个操作虽然请不了数据, 但是还是得留着清理调单校验错误提示
      // resetFields()的方法清不了form.id导致的   需要手动清理数据
      this.$refs.formData.resetFields()
      // 关弹窗
      this.isShowDialog = false
    },
    async editRole(id) {
      const res = await getIdRole(id)
      console.log(res)
      this.formData = res
      this.isShowDialog = true
    },
    async showPermDialog(roleId) {
      // 编辑角色权限, 拿到角色id
      // 根据id获取角色原数据
      // 填充到当前选中的 权限 checkList 当中
      this.currentId = roleId
      const res = await getIdRole(roleId)
      console.log('点击分配权限, 获取当前点击角色详情', res)
      this.checkList = res.permIds
      this.isShowpremDialog = true
    },
    async btnPermOK() {
      // 发送请求
      await assignPerm({
        id: this.currentId,
        permIds: this.checkList
      })
      // 提示用户
      this.$message.success('操作成功')
      // 关闭弹窗
      this.isShowpremDialog = false
    },
    btnPermCancel() {
      // 关闭弹窗
      this.isShowpremDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.tool-bar {
  margin-bottom: 20px;
}
.page-bar {
  margin-top: 20px;
}
</style>
